package com.nega.commons.email;

import com.nega.modules.service.ConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @Author: Garcia
 * @CreateDate: 2019/5/20 19:43
 * @Description: what it is class?
 */
@Component
@Slf4j
public class MailCoreServer {

    @Resource
    private JavaMailSenderImpl javaMailSender;

    @Resource
    private ConfigService configService;

    public void sendEmail(EmailData emailData) {
        try {
            configMail();
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(javaMailSender.getUsername());
            helper.setTo(emailData.getRecipient());
            helper.setSubject(emailData.getSubject());
            helper.setText(emailData.getContent(), true);
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            log.error("邮件发送异常", e);
        }
    }

    private void configMail() {
        String emailHost = configService.getProperty("emailHost");
        String emailUsername = configService.getProperty("emailUsername");
        String emailPassword = configService.getProperty("emailPassword");
        javaMailSender.setHost(emailHost);
        javaMailSender.setUsername(emailUsername);
        javaMailSender.setPassword(emailPassword);
        javaMailSender.setDefaultEncoding("UTF-8");
    }
}
